import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  UploadedFiles,
  UseInterceptors,
  UseGuards,
  Query,
} from '@nestjs/common';
import { AnFileService } from './an-file.service';
import { CreateAnFileDto } from './dto/create-an-file.dto';
import { UpdateAnFileDto } from './dto/update-an-file.dto';
import { FindAnFileDto } from './dto/find-an-file.dto';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { FilesInterceptor } from '@nestjs/platform-express';
import { FastDFSService } from 'src/common/core/fastdfs/fastdfs.service';

@ApiTags('附件')
@Controller('api/file')
export class AnFileController {
  constructor(
    private readonly anFileService: AnFileService,
    private readonly fastDFSservice: FastDFSService,
  ) {}

  @Post('upload')
  @ApiOperation({ summary: '上传附件' })
  @UseInterceptors(FilesInterceptor('files'))
  async create(
    @UploadedFiles() files,
    @Body() createAnFileDto: CreateAnFileDto,
  ) {
    const resDate = [];
    for (const file of files) {
      // 创建新的对象  避免数据污染
      const newFileObj = new CreateAnFileDto();
      Object.assign(newFileObj, createAnFileDto);
      // 保存到数据库
      const res = await this.anFileService.create(file, newFileObj);
      resDate.push({
        id: res.id,
        filename: res.name,
        path: res.path,
      });
    }
    return resDate;
  }

  @Get('list')
  @ApiOperation({ summary: '列表' })
  findAll(@Query() query: FindAnFileDto) {
    return this.anFileService.findAll(query);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.anFileService.findOne(id);
  }

  @Post('/update')
  update(@Query('id') id: string, @Body() updateAnFileDto: UpdateAnFileDto) {
    return this.anFileService.update(id, updateAnFileDto);
  }

  @Post('delete')
  async remove(@Query('ids') ids: string) {
    const aryIds = ids.split(',');
    this.anFileService.remove(aryIds);
    return '删除成功！';
  }
}
